package com.dd.ms.log.web.config.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.support.converter.StringJsonMessageConverter;
import org.springframework.kafka.support.serializer.JsonDeserializer;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/6/28 12:53
 * @Description KafkaConsumerConfig
 */
@Configuration
public class KafkaConsumerConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Value("${spring.kafka.consumer.group-id}")
    private String consumerGroupId;

    @Value("${spring.kafka.consumer.concurrency}")
    private int concurrency;  // 消费者并发数（线程数）

    @Bean
    public ConsumerFactory<String, Object> consumerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerGroupId);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
        /**
         🟥[TRUSTED_PACKAGES必须指定 否则报错] 添加JsonDeserializer的信任包配置 JsonUserBO所在的包
         🟢[TRUSTED_PACKAGES如何指定多个包？]
         (1) 逗号间隔
             props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.dd.stack.kafka.common.pojo.dto,com.example.pkg1,com.example.pkg2");
         (2) 使用通配符
             props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.dd.stack.kafka.*,org.example.*");
         */
        props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.dd.ms.log.api.pojo.dto");
        // 关闭自动提交
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        return new DefaultKafkaConsumerFactory<>(props);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        // 配置消息转换器
        factory.setMessageConverter(new StringJsonMessageConverter());
        // 关键：设置并发消费者数量
        factory.setConcurrency(concurrency);
        // 手动立即提交偏移量
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
        return factory;
    }
}
